package org.social.quartz;

import com.google.common.collect.Lists;
import com.sojoys.artifact.constant.DataModelKeyEnum;
import com.xiaoleilu.hutool.date.DateUtil;

import org.constant.StoreConstant;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.remote.game.RemoteGameServer;
import org.social.db.bean.DynamicCommodity;
import org.social.db.cache.DynamicCommodityCache;
import org.social.manager.ActivityManager;
import org.social.manager.NoticeManager;
import org.utils.RemoteUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author : DengYing
 * @CreateDate : 2017年8月24日 下午12:27:59
 * @Description ：每秒定时器
 */
public class SecondsJob implements Job {
	static Date LAST_EXECUTE_DATE = new Date();

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// 检查全服限购商品刷新

		// 检查动态商品
		checkDynamicCommodity();

		// 检查活动状态
		ActivityManager.me().checkActivityStatus();
		
		Date nowDate = new Date();
		if(DateUtil.betweenDay(LAST_EXECUTE_DATE, nowDate, true)!=0){
			RemoteUtil.gameTopic().newDay(nowDate);
			LAST_EXECUTE_DATE = nowDate;
		}
	}

	/**
	 * 检查动态商品
	 */
	public void checkDynamicCommodity() {
		List<DynamicCommodity> all = DynamicCommodityCache.me().loadAll();
		Date nowDate = new Date();
		// 需要上架的商品
		List<Map> added = Lists.newArrayList();
		// 需要下架的商品
		List<Map> shelf = Lists.newArrayList();

		List<DynamicCommodity> saveList = Lists.newArrayList();
		for (DynamicCommodity dynamicCommodity : all) {
			// 状态
			int status = dynamicCommodity.getStatus();

			switch (status) {
			case StoreConstant.DEFAULT_STATUS:
				if (dynamicCommodity.getAddedTime() == null || dynamicCommodity.getAddedTime().after(nowDate)) {
					added.add(dynamicCommodity.toMap(DataModelKeyEnum.SOURCE));
					dynamicCommodity.setStatus(StoreConstant.ADDED_STATUS);
					saveList.add(dynamicCommodity);
				}
				break;
			case StoreConstant.ADDED_STATUS:
				if (dynamicCommodity.getShelfTime() == null || dynamicCommodity.getShelfTime().after(nowDate)) {
					shelf.add(dynamicCommodity.toMap(DataModelKeyEnum.SOURCE));
					dynamicCommodity.setStatus(StoreConstant.SHELF_STATUS);
					saveList.add(dynamicCommodity);
				}
				break;
			case StoreConstant.SHELF_STATUS:

				break;
			}
		}

		// 批量存储修改的动态商品
		if (!saveList.isEmpty()) {
			DynamicCommodityCache.me().updateBatch(saveList);
		}

		if (!added.isEmpty() || !shelf.isEmpty()) {
			// 广播游戏服务器需要上架、下架的商品
			RemoteGameServer remoteGameServer = RemoteUtil.gameTopic();
			remoteGameServer.syncDynamicCommodity(added, shelf);
		}
	}

	private void checkMarqueeNotice() {

	}

	private void checkBillboardNotice() {

	}

}
